﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace JinJun.YShow.Core
{
  public  class DataTableHelper
    {

        /// <summary>
        /// 将数据集信息绑定到List集合对象中方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dataTable) {
            //创建T集合
            List<T> list = new List<T>();
            //循环表格的行数
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                //实例化
                T t = Activator.CreateInstance<T>();
                //获取T所有属性
                PropertyInfo[] propertyinfo = t.GetType().GetProperties();
                //循环每一列
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    foreach (PropertyInfo pro in propertyinfo)
                    {
                        //找到对应的属性
                        if (pro.Name.ToLower()==dataTable.Columns[j].ColumnName.ToLower())
                        {
                            //判断具体的哪一行哪一列的值是否为空
                            if (dataTable.Rows[i][j] != DBNull.Value)
                            {
                                pro.SetValue(t,dataTable.Rows[i][j]);
                            }
                            else {
                                pro.SetValue(t,null);
                            }
                        }
                    }
                }
                //将t添加到T集合
                list.Add(t);
            }
            return list;
        }
    }
}
